import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:sports_new/entity/other/app_update_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/server/api/other_api.dart';
import 'package:sports_new/server/http/dio_utils.dart';
import 'package:sports_new/server/http/request_header.dart';
import 'package:sports_new/utils/app_config.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/update_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/my/account/my_account_page.dart';
import 'package:sports_new/view/my/ali_im_test_page.dart';
import 'package:sports_new/view/my/my_aboutus_page.dart';
import 'package:sports_new/view/my/personal_ads_page.dart';
import 'package:sports_new/view/my/socket_page.dart';
import 'package:sports_new/view/my/widgets/my_appbar.dart';
import 'package:sports_new/view/my/widgets/my_cellbox.dart';
import 'package:sports_new/widgets/base/qkd_bottomsheet.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';
import 'package:sports_new/widgets/resource_dialog.dart';

import '../../widgets/base/qkd_text.dart';

class MySettingsPage extends StatefulWidget {
  const MySettingsPage({super.key});

  @override
  State<MySettingsPage> createState() => _MySettingsPageState();
}

class _MySettingsPageState extends State<MySettingsPage> {
  tapUserInfo() => User.needLogin(() => Get.toNamed(Routes.myEditInfo));
  tapAboutUs() => Get.to(const MyAboutUsPage());
  tapPushSetting() {
    Utils.onEvent("tssz");
    Get.toNamed(Routes.myPushSetting);
  }

  tapAccountSafe() => User.needLogin(() => Get.to(() => const MyAccountPage()));
  tapAds() => Get.to(const PersonalAdsPage());

  PackageInfo? pinfo;
  AppUpdateEntity? updateinfo;
  String? proxyUrl;

  String get updateDesc => (updateinfo?.getNeedUpdate ?? false)
      ? "发现新版本${updateinfo?.latestVersion}"
      : "当前版本${pinfo?.version}";

  checkAppUpdate() async {
    final version = pinfo?.version;
    if (version == null) {
      return;
    }
    updateinfo = await OtherApi.checkUpdate(version);
    update();
  }

  @override
  void initState() {
    PackageInfo.fromPlatform().then((value) {
      pinfo = value;
      checkAppUpdate();
      update();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.scaffoldBg,
      appBar: MyAppBar(
        title: "设置",
        actions: [
          if (AppConfig.config.isDebug)
            const Icon(Icons.settings).tap(() {
              Get.bottomSheet(_baseUrlSetSheet());
            }).marginOnly(right: 8)
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Column(
          children: [
            const SizedBox(
              height: 8,
            ),
            cellBox([cell("编辑资料").tap(tapUserInfo)]),
            const SizedBox(
              height: 8,
            ),
            cellBox([cell("推送设置").tap(tapPushSetting)]),
            const SizedBox(
              height: 8,
            ),
            cellBox([cell("账号与安全").tap(tapAccountSafe)]),
            const SizedBox(
              height: 8,
            ),
            cellBox([cell("个性化广告").tap(tapAds)]),
            const SizedBox(height: 8),
            cellBox([
              if (Platform.isAndroid) wlanCell(),
              if (Platform.isAndroid)
                Utils.divider().marginSymmetric(horizontal: 12),
              updateCell().tap(() {
                if (updateinfo?.getNeedUpdate ?? false) {
                  SpUtils.versionIgnoreSet = updateinfo?.latestVersion;
                }
                update();
                UpdateUtils.checkUpdate();
              })
            ]),
            const SizedBox(
              height: 8,
            ),
            cellBox([
              if (AppConfig.config.isDebug) ...[
                cell("socket测试").tap(() => Get.to(() => const SocketPage())),
                cell("阿里im测试").tap(() => Get.to(() => const AliImTestPage())),
                cell("错误信息").tap(() => Get.toNamed(Routes.error))
              ],
              cell("关于我们").tap(tapAboutUs),
              // Utils.divider().marginSymmetric(horizontal: 12),
              // cell("账号注销"),
            ]),
            const SizedBox(height: 20),
            if (User.isLogin) logoutBtn()
          ],
        ),
      ),
    );
  }

  Widget logoutBtn() => cellBox([
        Container(
          height: 52,
          color: Colors.white,
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              QkdText("退出登录", fontSize: 16),
            ],
          ),
        ).tap(() async {
          if (User.auth?.type == 0) {
            final value = await Get.dialog(QkdDialog.alert('游客账号退出提醒',
                content: '退出登录后，您的数据将会丢失。',
                confirmText: '确认退出',
                cancelText: '暂不退出'));
            if (value == true) {
              await User.doLogRefresh(isLogin: false);
              update();
              Get.back();
            }
          } else {
            final value = await WidgetUtils.alertQuery("确定退出登录吗？");
            if (value == true) {
              await User.doLogRefresh(isLogin: false);
              Get.back();
              update();
              Get.back();
            }
          }
        })
      ]);

  Widget wlanCell() => cell("WLAN环境下自动下载新版本",
      right: CupertinoSwitch(
        activeColor: Colours.main,
        value: SpUtils.autoDownload ?? true,
        onChanged: (value) {
          SpUtils.autoDownload = value;
          setState(() {});
        },
      ));

  Widget updateCell() => cell("检查更新",
      right: Row(
        children: [
          QkdText(updateDesc, needCenter: true, color: Colours.grey66),
          if ((updateinfo?.getNeedUpdate ?? false) &&
              updateinfo?.latestVersion != SpUtils.versionIgnoreSet) ...[
            Container(width: 4),
            Container(
                width: 6,
                height: 6,
                decoration: const BoxDecoration(
                    shape: BoxShape.circle, color: Colours.main)),
            Container(width: 2),
          ] else ...[
            Container(width: 8)
          ],
          Image.asset(Utils.getImgPath("icon_arrow_right.png"),
              width: 6, height: 10)
        ],
      ));

  Widget cellBox(List<Widget> children) => MyCellBox(children: children);

  Widget cell(String text, {Widget? right}) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        height: 52,
        child: Row(
          children: [
            QkdText(text, fontSize: 16),
            const Spacer(),
            if (right != null) right,
            if (right == null)
              Image.asset(Utils.getImgPath("icon_arrow_right.png"),
                  width: 6, height: 10)
          ],
        ),
      );

  Widget _baseUrlSetSheet() {
    final list = [
      ["开发 : ", Constant.devBaseUrl],
      ["测试 : ", Constant.testBaseUrl],
      ["生产 : ", Constant.prodBaseUrl]
    ];

    final cur = DioUtils.baseUrl;
    final stored = SpUtils.baseUrl;

    // ignore: prefer_function_declarations_over_variables
    final btn = (List<String> l, FutureOr Function()? click) {
      bool isCur = cur == l[1];
      bool isCheck = stored == l[1];
      return Container(
        height: 44,
        child: Row(
          children: [
            QkdText(l[0]),
            QkdText(l[1], color: isCur ? Colors.red : null),
            const Spacer(),
            if (isCheck) const Icon(Icons.check, size: 16)
          ],
        ),
      ).tap(click);
    };

    return QkdBottomSheet(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            QkdText("token").marginOnly(right: 10),
            Expanded(child: QkdText(User.auth?.token ?? "", maxLines: 3)),
            const Icon(Icons.copy)
                .paddingSymmetric(horizontal: 10, vertical: 8)
                .tap(() async {
              if (await Get.dialog(QkdDialog.alert("复制token?")) ?? false) {
                Clipboard.setData(ClipboardData(text: User.auth?.token ?? ""))
                    .then((value) => ToastUtils.show("已复制"));
              }
            })
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            QkdText("更换baseUrl ${pinfo?.version ?? ""}(${pinfo?.buildNumber ?? ""})",
                    fontSize: 20, fontWeight: FontWeight.w500)
                .marginSymmetric(vertical: 10),
            // Spacer(),
            Expanded(
              child: IconButton(
                  onPressed: () =>
                      ToastUtils.showDismiss(RequestHeader.print(), 10),
                  icon: const Icon(Icons.info)),
            ),
            Expanded(
              child: IconButton(
                  padding: EdgeInsets.zero,
                  onPressed: () => Get.toNamed(Routes.error),
                  icon: const Icon(Icons.nearby_error)),
            ),
            Expanded(
              child: IconButton(
                  onPressed: () async {
                    // ToastUtils.showDismiss(HeaderDeviceInfo.descrption, 10);
                    final b =
                        await Get.dialog(QkdDialog.alert("清除一些缓存")) ?? false;
                    if (b) {
                      SpUtils.gift4newuser = {};
                      SpUtils.notifySetted = false;
                      SpUtils.lbtDialogIds = null;
                      ResourceDialogUtil.showedLbts = [];
                    }
                  },
                  icon: const Icon(Icons.delete)),
            ),
          ],
        ),
        ...list.map((e) => btn(e, (() {
              Get.dialog(QkdDialog.alert("更换base url ${e[1]}\n需要重启生效"))
                  .then((value) {
                if (value ?? false) {
                  SpUtils.baseUrl = e[1];
                  Get.back();
                }
              });
            }))),
        QkdButton(
            text: SpUtils.proxyEnabled ? '关闭代理' : '开启代理',
            onPressed: () async{
              
              if (!SpUtils.proxyEnabled) {
                showProxyDialog();
              } else {
                SpUtils.proxyEnabled = !SpUtils.proxyEnabled;
                await Get.dialog(QkdDialog.single('重启后生效'));
                exit(0);
              }
            }),
        const SizedBox(height: 80)
      ],
    ));
  }

  void showProxyDialog() {
    Get.dialog(
      AlertDialog(
        title: Text('请输入代理地址，例：192.168.0.0:8888'),
        content: TextField(
          
          onChanged: (String value) {
            // input = value;
            proxyUrl = value;
          },
        ),
        actions: <Widget>[
          QkdButton(text: 'cancel',onPressed: () {
            Get.back();
          }),
          QkdButton(text: 'ok',onPressed: () async{
            SpUtils.proxyEnabled = !SpUtils.proxyEnabled;
            SpUtils.proxyUrl = proxyUrl ?? '';
            // Get.back();
            await Get.dialog(QkdDialog.single('重启后生效'));
            exit(0);
          })
          
        ],
      )
    );
  }
}
